export const trimSlash = url => url.replace(/^\/+|\/+$/g, '')

export const joinUrl = (...urls) => urls.filter(Boolean).map(trimSlash).join('/')

export const trimProtocol = url => url.replace(/^http:\/\/|https:\/\//ig, '')

export const trimRegexFlag = url => url.replace(/^regex:/i, '')

export const trimQueryString = url => url.replace(/\?.*/, '')

export const equalUrlAfterTrimProtocol = (url1, url2) => trimProtocol(url1) === trimProtocol(url2)

export const urlIsRegex = url => /regex:/i.test(url)

export const genKeyValueArraysFromQueryString = queryString => queryString.split('&').map(item => item.split('=').map(val => val.trim()))     // a=1&b=2  => [[a,1], [b,2]]

export const extractParamNames = rawParams => genKeyValueArraysFromQueryString(rawParams).map((([key, value]) => key))    // a&b => [a, b],   a=1&b=2  => [a,b]

// a=1&b=2 => { a: 1, b: 2}
export const genKeyValueObjectFromQueryString = queryString => genKeyValueArraysFromQueryString(queryString).reduce((result, [key, value]) => { result[key] = value; return result; }, {})

export const extractRequestParamsToObject = request => {
    const method = request.method()
    let currentParamObject = {}
    const url = request.url()

    if (method === 'GET') {
        const queryString = url.indexOf('?') > 0 ? url.replace(/.*?\?/, '') : ''
        currentParamObject = genKeyValueObjectFromQueryString(queryString)
    } else if (method === 'POST') {
        try {
            currentParamObject = JSON.parse(request.postData())
        } catch (error) {
            throw `invalid param value in ${request.url()}, expected to be valid json string`
        }
    } else {
        throw `not supoort method http method: ${method} in network equal assert, only support method: GET, POST`
    }

    return currentParamObject
}

export const getUrlOfEnv = (url, env = { host: '' }) => {
    if (!url) {
        throw 'url is supposed to be not empty'
    }

    if (url.indexOf('http://') === 0 || url.indexOf('https://') === 0) {
        return url
    } else {
        const { host } = env

        return joinUrl(host, url)
    }
}

export const getIfMatch = (url, env) => {
    const mockUrlIsRegex = urlIsRegex(url)
    const trimRegexUrl = trimRegexFlag(url)
    const regex = mockUrlIsRegex ? new RegExp(trimRegexUrl) : null
    const urlOfEnv = getUrlOfEnv(trimRegexUrl, env) // 支持不带http:// 或者 https:// 打头的相对路径

    const ifMatch = currentUrl => {
        if (mockUrlIsRegex) {
            return regex.test(currentUrl) // 支持正则匹配模式
        } else {
            const currentUrlAfterTrimQuery = trimQueryString(currentUrl)
            const urlOfEnvAfterTrimQuery = trimQueryString(urlOfEnv)

            return equalUrlAfterTrimProtocol(currentUrlAfterTrimQuery, urlOfEnvAfterTrimQuery)
        }
    }

    return ifMatch
}